<template>
  <div class="create-settle">
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="closeDialog"
      :show-close="!showMobilePage"
      :append-to-body="true"
      :close-on-click-modal="true"
      :class="{'global-mobile-dialog':showMobilePage}"
      class="large-common-dialog-size create-settle-dialog"
    >
      <Title title="结算单信息" font-size="16px" style="margin-bottom:16px;"/>
      <el-row class="create-form" >
        <el-form ref="form" :model="paramsObj" :rules="rules" :class="{'mobile-el-form': showMobilePage}" :label-position="showMobilePage?'left':'right'" label-width="100px">
          <el-col :span="12">
            <el-form-item label="供应商名称" label-width="100px" prop="supplierName">
              <el-input v-model="paramsObj.supplierName" placeholder="请输入供应商名称" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="clientCompany">
              <el-select
                v-model="paramsObj.clientCompany"
                :remote-method="searchClientName"
                :loading="loading1"
                class="filterableSelect remoteRequestClient"
                popper-class="global-select-down"
                allow-create
                filterable
                remote
                placeholder="搜索匹配"
                size="small">
                <el-option
                  v-for="item in clientNameOp"
                  :key="item.id"
                  :label="item.value"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label-width="showMobilePage?'100px':'97px'" label="结算总金额:" class="gray-label">
              <span class="item-text">
                {{ (totalPrice / 100) | moneyFilter }}元
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算总订单数:" class="gray-label">
              <span class="item-text">
                {{ paramsObj.orderIds.length }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算日期" label-width="100px" prop="settleStartTime">
              <el-date-picker
                v-model="dateRange"
                :editable="false"
                clearable
                size="small"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                format="yyyy/MM/dd"
                @change="datePickerTime" />
            </el-form-item>
          </el-col>
          <el-col v-if="remark" :span="24">
            <el-form-item :label-width="showMobilePage?'100px':'85px'" :style="`${showMobilePage? '' : 'padding-left:12px;'}`" label="驳回理由">
              <div>{{ remark }}</div>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="order-list">
        <div class="order-list-top" style="margin-bottom:5px;">
          <!-- <Title title="订单列表" font-size="16px" style="margin-top: 14px;"/> -->
          <DetailTabs v-model="currentTab" :tabs="tabList" style="padding: 10px 0;" @tabClick="handleTabClick" />
        </div>
        <div :style="{maxHeight: tableHeight + 'px'}" class="content scroll">
          <detailOrderFilter
            v-show="!onlyShowSelect"
            ref="filterRef"
            :dialog-visible="dialogVisible"
            style="margin-bottom:10px;"
            @searchData="getData" />
          <orderTable
            ref="settleOrderTable"
            :loading="loading"
            :only-show-select="onlyShowSelect"
            :client-order="onlyShowSelect?{items: selectOrder}:clientOrder"
            :select-order="clientOrder"
            @handleSelectionChange="handleSelectionChange"
            @closeDialog="isClose" />
        </div>

        <div class="foot-container">
          <div class="opeator">
            <el-button :loading="bthLoading" :disabled="paramsObj.orderIds.length === 0" type="primary" size="small" @click="toSubmit">{{ isEdit?'重新提交' : '生成' }}结算单</el-button>
          </div>
          <el-pagination
            v-if="!onlyShowSelect"
            :current-page="page"
            :page-size="perPage"
            :total="clientOrder.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="showMobilePage?'total, prev, next':'total, prev, pager, next, sizes, jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
    </el-dialog>
    <Dialog
      ref="createDialogRef"
      :allDeptList="allDeptList"
      :btn1="'确认'"
      :btn2="'取消'"
      :auth-url="authUrl"
      :class="{'global-mobile-dialog':showMobilePage}"
      summary="请确认是否生成结算单并提交审批"
      title="结算单生成确认"
      @handelOK="toCreateEdit" />
  </div>
</template>

<script>
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import Title from '@/components/Title';
import detailOrderFilter from '@/components/Customer/detail/customerDataFilter';
import Dialog from './detail/dialog';
import orderTable from './table';
import { createSettlement, editSettlement, getClientOrderList } from '@/api/customer';
import { getClientName } from '@/api/select';
import { moneyFilter } from '@/filters/number';
import ElMessage from '@/utils/message';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { mapState } from 'vuex';

export default {
  components: {
    Title,
    detailOrderFilter,
    orderTable,
    DetailTabs,
    Dialog },
  filters: { moneyFilter },
  props: {
    customerId: {
      type: String,
      default: ''
    },
    notJump: {
      type: Boolean,
      default: false
    },
    // 弹窗是否首次打开
    init: {
      type: Boolean,
      default: true
    }
  },
  data() {
    const validateTime = (msg) => {
      return (rule, value, callback) => {
        const start = this.paramsObj.settleStartTime;
        const end = this.paramsObj.settleEndTime;
        if (start && end) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    };
    return {
      settlementId: '',
      currentTab: 0,
      isEdit: false,
      loading1: false,
      clientNameOp: [],
      remark: '',
      tableHeight: 260,
      dialogVisible: false,
      dateRange: [],
      rules: {
        settleStartTime: [{ required: true, trigger: 'change', validator: validateTime('请选择结算时间') }],
        supplierName: [{ required: true, trigger: 'change', message: '请输入供应商名称' }],
        clientCompany: [{ required: true, trigger: 'change', message: '请选择客户名称' }]
      },
      paramsObj: {
        supplierName: '厦门飞博共创网络科技股份有限公司',
        clientCompany: '',
        settleStartTime: '',
        settleEndTime: '',
        orderIds: []
      },
      loading: false,
      page: 1,
      perPage: 20,
      selectOrder: [],
      clientOrder: {
        items: [],
        total: 0
      },
      bf: [],
      bthLoading: false,
      // init: true,
      routeOrderId: '',
      routeClientName: '',
      allDeptList: [],
      // 钉钉通知人员列表，筛选有审批权限的人
      authUrl: 'crm:customer:examine',
      // 是否打开页面首次请求
      requestFirst: true,
      rangeKeyArr: [{
        attr: 'orderTime',
        start: 'orderStartTime',
        end: 'orderEndTime',
        type: 'time'
      }, {
        attr: 'arrivalTime',
        start: 'arrivalStartTime',
        end: 'arrivalEndTime',
        type: 'time'
      }, {
        attr: 'taxAmount',
        start: 'taxAmountStart',
        end: 'taxAmountEnd',
        type: 'number'
      }]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    totalPrice() {
      const all = this.selectOrder.reduce((total, currentValue) => {
        const price = currentValue ? currentValue.taxAmount : 0;
        return price + total;
      }, 0);
      return all;
    },
    onlyShowSelect() {
      return this.currentTab === 1;
    },
    tabList() {
      const num = this.selectOrder.length;
      return [
        { id: 0, name: '全部订单' },
        { id: 1, name: '已选择订单', num: num }
      ];
    }
  },
  mounted() {
    window.remoteRequest('.remoteRequestClient', this.clientNameList);
  },
  methods: {
    getData(reset = false) {
      if (reset) this.page = 1;
      const params = this.$refs.filterRef ? JSON.parse(JSON.stringify(this.$refs.filterRef.paramsObj)) : {};
      params.page = this.page;
      params.perPage = this.perPage;
      params.enter = 2; // 从哪里请求 1、客户详情 2、创建或编辑结算单
      params.processArr = params.processArr ? params.processArr.join(',') : '';
      // 时间处理
      /* if (params.orderTime && params.orderTime.length === 2) {
        params.orderStartTime = Math.round(params.orderTime[0] / 1000);
        params.orderEndTime = Math.round(params.orderTime[1] / 1000);
      }
      if (params.arrivalTime && params.arrivalTime.length === 2) {
        params.arrivalStartTime = Math.round(params.arrivalTime[0] / 1000);
        params.arrivalEndTime = Math.round(params.arrivalTime[1] / 1000);
      }
      if (params.taxAmount && params.taxAmount.length === 2) {
        params.taxAmountStart = params.taxAmount[0] || params.taxAmount[0] === 0 ? Number(params.taxAmount[0]) : null;
        params.taxAmountEnd = params.taxAmount[1] || params.taxAmount[1] === 0 ? Number(params.taxAmount[1]) : null;
      }
      delete params.orderTime;
      delete params.arrivalTime;
      delete params.taxAmount; */
      paramsRangeFormat(this.rangeKeyArr, params);
      this.loading = true;
      if (this.settlementId) params.settleId = this.settlementId;
      getClientOrderList(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          // 从渠道订单详情页跳转，路由上有带上订单编号和客户名称
          // 弹窗是新页面首次打开并且是首次请求
          // 设置默认选中的订单
          if (this.routeOrderId && this.routeClientName && this.init && this.requestFirst) {
            this.selectOrder = res.data.items.length > 0 ? [res.data.items.find(i => i.orderId === this.routeOrderId)] : [];
            this.$set(this.paramsObj, 'orderIds', [this.selectOrder[0].id]);
          }
          // 获取选中的订单id，放入数组中。并将订单列表里被选中订单的选中状态改为true
          const selectOrderIds = this.selectOrder.map(i => i.id);
          res.data.items.map(i => {
            this.$set(i, '_check', false);
            i = Object.assign(i, i.orderInfo, i.financeRecord);
            if (selectOrderIds.includes(i.id)) this.$set(i, '_check', true);
            return i;
          });
          this.clientOrder = res.data;
          this.$nextTick(() => {
            if (this.$refs.settleOrderTable) this.$refs.settleOrderTable.checkAllOrder();
          });
        }
        this.requestFirst = false;
      }).catch(() => {
        this.loading = false;
        this.requestFirst = false;
      });
    },
    // 获取客户名称列表
    clientNameList(query = null) {
      this.loading1 = true;
      const param = {
        clientName: query,
        isGetMengliClient: false
      };
      getClientName(param).then(res => {
        this.loading1 = false;
        this.clientNameOp = res.data;
      }, result => {
        this.loading1 = false;
        // this.$message.error(result.message);
      });
    },
    // 查询客户名称列表
    searchClientName(query) {
      this.clientNameList(query);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getData();
    },
    isClose(val) {
      this.closeDialog();
    },
    // 保存或删除已选中的订单，支翻页选中
    handleSelectionChange({ order, select }) {
      if (select) {
        if (this.selectOrder.length === 0) {
          this.selectOrder = order;
        } else {
          const selectOrderIds = this.selectOrder.map(i => i.id);
          const concatOrder = order.filter(i => !selectOrderIds.includes(i.id));
          this.selectOrder = this.selectOrder.concat(concatOrder);
        }
      } else {
        const orderIds = order.map(i => i.id);
        this.selectOrder = this.selectOrder.filter(i => {
          return !orderIds.includes(i.id);
        });
      }
      this.paramsObj.orderIds = this.selectOrder.map(i => i.id);
    },
    openDialog(data = {}, isEdit = false, isBackfill = false) {
      // 从渠道订单详情页跳转，带上订单编号和客户名称
      if (this.init) {
        this.routeOrderId = this.$route.query.orderId || null;
        this.routeClientName = this.$route.query.clientName || null;
      }
      this.dialogVisible = true;
      const clientHeight = window.innerHeight;
      this.tableHeight = (clientHeight * 2) / 5 + 30;
      this.isEdit = isEdit || false;
      this.settlementId = data.id;
      if (this.isEdit) this.currentTab = 1;
      if (data.remark) {
        this.remark = data.remark;
      } else {
        this.remark = '';
      }
      let orderIds = [];
      if (data.items && data.items.length) {
        orderIds = data.items.map(i => {
          i._check = true;
          return i.id;
        });
      }
      this.paramsObj = {
        supplierName: data.supplierName || '厦门飞博共创网络科技股份有限公司',
        clientCompany: this.routeClientName || data.clientCompany || '',
        settleStartTime: data.settleStartTime || '',
        settleEndTime: data.settleEndTime || '',
        orderIds
      };
      if (data.settleStartTime && data.settleEndTime) this.dateRange = [data.settleStartTime, data.settleEndTime];
      this.selectOrder = data.items || [];

      this.$nextTick(() => {
        if (this.$refs.filterRef && (isBackfill || this.routeClientName)) this.$set(this.$refs.filterRef.paramsObj, 'clientName', this.paramsObj.clientCompany);
        if (this.$refs.filterRef && this.routeOrderId) this.$set(this.$refs.filterRef.paramsObj, 'orderId', this.routeOrderId);
        this.getData(true);
        this.clientNameList();
      });
    },
    closeDialog() {
      this.dialogVisible = false;
      this.currentTab = 0;
      this.dateRange = [];
      this.paramsObj.settleStartTime = '';
      this.paramsObj.settleEndTime = '';
      this.routeOrderId = '';
      this.routeClientName = '';
      this.page = 1;
      // 设置弹窗是否为首次打开展示填充内容
      this.$emit('openStatus', false);
    },
    datePickerTime(e) {
      if (e && e.length === 2) {
        this.paramsObj.settleStartTime = e[0];
        this.paramsObj.settleEndTime = e[1];
      } else {
        this.paramsObj.settleStartTime = '';
        this.paramsObj.settleEndTime = '';
      }
    },
    toSubmit() {
      // const paramsObj = this.paramsObj;
      // if (!paramsObj.supplierName) {
      //   ElMessage.error('请填写供应商名称');
      //   return;
      // }
      // if (!paramsObj.clientCompany) {
      //   ElMessage.error('请填写客户公司名称');
      //   return;
      // }
      // if (!paramsObj.settleStartTime || !paramsObj.settleEndTime) {
      //   ElMessage.error('请选择结算时间');
      //   return;
      // }
      this.$refs.form.validate(valid => {
        if (valid) {
          const msg = '您有新待审批结算单，请及时处理';
          this.$refs.createDialogRef.showDialog({ defaultMsg: msg });
        } else {
          ElMessage.warning('请检查信息是否填写完整');
        }
      });
    },
    toCreateEdit(data) {
      // 提交创建或编辑结算单
      // 添加钉钉通知配置
      const paramsObj = this.paramsObj;
      Object.assign(paramsObj, data);
      if (!this.isEdit) {
        this.toCreate(paramsObj);
      } else {
        paramsObj.id = this.settlementId;
        this.toEdit(paramsObj);
      }
    },
    toEdit(params) {
      this.bthLoading = true;
      editSettlement(params).then(res => {
        this.bthLoading = false;
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.$emit('getData', res.data);
          this.closeDialog();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.bthLoading = false;
        console.error(err);
      });
    },
    toCreate(params) {
      this.bthLoading = true;
      createSettlement(params).then(res => {
        this.bthLoading = false;
        if (res.code === 200) {
          this.$message.success('创建成功');
          this.$emit('getData', res.data);
          // if (res.data) {
          //   this.$router.push({
          //     name: 'settleCustomer',
          //     params: { tab: 'all' }
          //   });
          // } else {
          //   this.$emit('getData');
          // }
          if (!this.notJump) {
            this.$router.push({
              name: 'customersettle'
            });
          }
          this.closeDialog();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.bthLoading = false;
        console.error(err);
      });
    },
    switchSelect() {
      const selectOrderIds = this.selectOrder.map(i => i.id);
      this.clientOrder.items.forEach(i => {
        i._check = selectOrderIds.includes(i.id);
      });
      this.$nextTick(() => {
        if (this.$refs.settleOrderTable) this.$refs.settleOrderTable.checkAllOrder();
      });
    },
    handleTabClick(e) {
      this.switchSelect();
    }
  }
};
</script>

<style lang="scss" scoped>
.scroll {
  @include scrollBar();
}
.create-form {
  &::v-deep {
    .el-input {
      width: 240px;
    }
    .el-form-item{
      height: 32px;
      margin-bottom: 16px;
    }
    .el-date-editor  {
      width: 240px;
    }
    .align-left {
      .el-form-item__label {
        text-align: left;
      }
    }
  }
  .gray-label {
    &::v-deep {
      .el-form-item__label {
        color: #999;
      }
    }
  }
  .item-text {
    color: #406EFF;
    font-size: 16px;
  }
}
.order-list {
  position: relative;
  margin-top: 10px;
  &::before {
    position: absolute;
    content: '';
    width: 1080px;
    height: 6px;
    background-color: #F7F7F7;
    left: -24px;
    top: -6px;
  }
}
.foot-container {
  display: flex;
  align-items: center;
  margin-top: 10px;
  height: 48px;
  .opeator {
    flex:1;
  }
}
</style>
<style lang="scss">
.create-settle-dialog {
  .el-dialog  {
    width: 1095px !important;
    .el-dialog__body {
      padding-bottom: 15px !important;
    }
  }
}
.global-mobile-dialog {
  .create-form {
    overflow-y: auto;
  }
  .el-dialog  {
    width: 100% !important;
    .el-dialog__body {
      max-height: 80vh;
      overflow-y: auto;
    }
    .order-list {
    &::before {
      width: 100%;
    }
  }
  }
  .mobile-el-form {
    .el-col {
      width: 100% !important;
    }
  }
}
</style>
